﻿using System;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.CodeGeneration;
using Medianamik.UI.Controls;
using Medianamik.UI.Web.UserControls;
using Telerik.Web.UI;

namespace Medianamik.UI.Web.TypeManagement
{
    public partial class TypeSearchResults : BasePage
    {
        private string _query;
        public string Query
        {
            get
            {
                if (_query == null)
                {
                    var q = Request.QueryString["q"] ?? string.Empty;
                    _query = HttpUtility.UrlDecode(q);
                }
                return _query;
            }
        }
        private int? _startPage;
        public int StartPage
        {
            get
            {
                if (!_startPage.HasValue)
                {
                    int p;
                    _startPage = int.TryParse(Request.QueryString["p"], out p) && p > 0 
                               ? p 
                               : 0;
                }
                return _startPage.Value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SearchResults.CurrentPageIndex = StartPage;
                var sb = MyMasterPage.FindControl("SearchBox") as SearchBox;
                if (sb != null)
                {
                    sb.SearchText = Query;
                }
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            SearchResults.Rebind();
        }

        protected void GridNeedDataSource(object sender, EventArgs e)
        {
            SearchResults.DataSource = NodeTypeManager.GetAllTypes(true)
                                      .Where(t => t.Name.Contains(Query, StringComparison.CurrentCultureIgnoreCase))
                                      .Skip(SearchResults.CurrentPageIndex * SearchResults.PageSize)
                                      .Take(SearchResults.PageSize);
        }

        protected void lnkGenTable_Click(object sender, CommandEventArgs e)
        {
            var code = new CodeService();
            NodeType t = NodeTypeManager.GetNodeType(new Guid((string)e.CommandArgument));
            code.GenerateTableAndView(t);
            code.FillTable(t);
        }

        protected void SearchResultsItemCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeleteType":
                    var type = NodeTypeManager.GetNodeType(new Guid(e.CommandArgument.ToString()));
                    if (!type.HasNodes && !type.HasChildren)
                    {
                        NodeTypeManager.DeleteNodeType(type);
                        SearchResults.Rebind();
                    }
                    break;
                default:
                    break;
            }
        }

        protected void SearchResultsItemDataBound(object sender, GridItemEventArgs e)
        {
            using (var gridDataItem = e.Item as GridDataItem)
            {
                if (gridDataItem != null)
                {
                    var type = (NodeType)gridDataItem.DataItem;

                    var link = e.Item.FindControl("lnkTypeName") as Literal;
                    if (link != null)
                    {
                        if (type.IsInheritable)
                        {
                            link.Text = "<a href=\"TypeList.aspx?basetypeid=" + type.ID + "\">" + type.Name + "</a>";
                        }
                        else if(type.HasParent)
                        {
                            link.Text = "<a href=\"TypeList.aspx?basetypeid=" + type.ParentID + "\">" + type.Name + "</a>";
                        }
                        else
                        {
                            link.Text = type.Name;
                        }

                    }

                    var btnDelete = e.Item.FindControl("btnDeleteType") as ImageButton;
                    if (btnDelete != null)
                    {
                        btnDelete.Enabled = !type.HasNodes && !type.HasChildren;
                    }
                    var btnEdit = e.Item.FindControl("btnEdit") as EditLink;
                    if (btnEdit != null)
                    {
                        btnEdit.NavigateUrl = GetUrl(type, "typeManagement.aspx");
                    }
                    var lnkPropertyList = e.Item.FindControl("lnkPropertyList") as HyperLink;
                    if (lnkPropertyList != null)
                    {
                        lnkPropertyList.NavigateUrl = GetUrl(type, "PropertyList.aspx");
                    }
                    var lnkSecurity = e.Item.FindControl("lnkSecurity") as HyperLink;
                    if (lnkSecurity != null)
                    {
                        lnkSecurity.NavigateUrl = GetUrl(type, "SecurityManagement.aspx");
                    }
                }
            }
        }

        protected string GetUrl(NodeType type, string pageUrl)
        {
            var url = pageUrl + "?" + Medianamik.Core.DefaultParamNames.TypeID + "=" + type.ID + "&fromSearch=" + Query;
            if (SearchResults.CurrentPageIndex > 0)
                url += "&page=" + SearchResults.CurrentPageIndex;
            return url;
        }

        protected override void OnCultureChanged(CultureChangedEventArgs e)
        {
            SearchResults.Rebind();
        }
    }
}
